<?php
namespace app\common\model\food;

use app\common\model\BaseModel;

/**
 * 餐桌/包间模型
 */
class Table extends BaseModel
{
    // 定义表名
    protected $name = 'food_table';

    // 定义主键
    protected $pk = 'table_id';

    // 追加字段
    protected $append = [];

    /**
     * 关联门店表
     */
    public function shop()
    {
        return $this->belongsTo('app\\common\\model\\food\\Shop','shop_id');
    }
    
    /**
     * 状态
     */
    public function getStatusAttr($value,$data)
    {
        $status = [10 => '空闲中', 20 => '使用中', 30 => '被预定'];
        $order_id = [];//订单编号
        $pay_price = 0;//待付款
        $time = '';//开单时间
        $list = Order::where(['table_id'=>$data['table_id'],'order_status'=>10])->order('create_time','desc')->select();
        if(sizeof($list)){
            foreach ($list as $item){
                $order_id[] = $item['order_id']; 
                if($item['pay_status']['value'] != 20){
                   $pay_price = $pay_price + $item['pay_price'];
                }
            }
            $value = 20;
            $time = round((time() - strtotime($list[0]['create_time']))/60);
        }
        if($pact = Pact::where(['table_id'=>$data['table_id'],'status'=>10])->order('pact_time','asc')->find()){
            $time = time() + 60*60*2;//提前两个小时不显示预约状态
            if($pact['pact_time'] > $time){
               $value = 30;
            }
        }
        return [
            'text' => $status[$value], 
            'value' => $value, 
            'order_id' => $order_id, 
            'time' => $time,
            'pay_price' => $pay_price,
            'pact' => $pact
        ];
    }

    /**
     * 获取列表
     */
    public function getList($shop_id = 0, $status = 0, string $search = '')
    {
        //筛选条件
        $filter = [];
        $shop_id > 0 && $filter['shop_id'] = $shop_id;
        !empty($search) && $filter['table_name'] = $search;
        // 执行查询
        $list = $this->with(['shop'])
            ->where($filter)
            ->order(['sort','table_id' => 'desc'])
            ->select();
        if($status > 0){
            $tablelist = $list;
            $list = [];
            for($n=0;$n<sizeof($tablelist);$n++){
                if($tablelist[$n]['status']['value'] == $status){
                    array_push($list,$tablelist[$n]);
                }
            }
        }
        return $list;
    }

    /**
     * 添加
     */
    public function add(array $data)
    {
        $data['applet_id'] = self::$applet_id;
        return $this->save($data);
    }
    
    
    /**
     * 编辑
     */
    public function edit(array $data)
    {
        return $this->save($data) !== false;
    }

    /**
     * 删除
     */
    public function remove()
    {
        return $this->delete();
    }

}
